import { createRouter, createWebHashHistory } from "vue-router";
import { ElMessage } from "element-plus";
import NProgress from "nprogress"; //进度条插件
import Cache from "@/utils/Cache";
const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login"),
  },
  {
    path: "/",
    name: "layout",
    component: () => import("@/views/layout"),
    children: [
      {
        path: "",
        name: "home",
        component: () => import("@/views/home"),
      },
      {
        path: "course",
        name: "course",
        component: () => import("@/views/course"),
      },
      {
        path: "book",
        name: "book",
        component: () => import("@/views/book"),
      },
      {
        path: "testpaper",
        name: "testpaper",
        component: () => import("@/views/testpaper"),
      },
      {
        path: "problems",
        name: "problems",
        component: () => import("@/views/problems"),
      },
      {
        path: "my",
        name: "my",
        component: () => import("@/views/my"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//路由守卫判断是否存在token导航到login页面
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.path !== "/login") {
    if (!Cache.getItem("token")) {
      ElMessage({
        message: "请先进行登录!",
        type: "warning",
        center: true,
      });
      next("/login");
      return;
    }
  }
  next();
});
router.afterEach(() => {
  NProgress.done();
});
export default router;
